package com.meituan.verintreport.task;

import com.meituan.verintreport.db.dao.FormsMapper;
import com.meituan.verintreport.db.dto.FormsDto;
import com.meituan.verintreport.db.verint.VerintBaseTableDao;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 全量数据同步
 */
@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "base-table.forms")
public class BaseTableTaskForms extends BaseTableTask {
    @Resource
    private FormsMapper formsMapper;

    @Resource
    private VerintBaseTableDao verintBaseTableDao;

    /**
     * 全量数据同步 12：30 每天
     */
    @Scheduled(cron = "${base-table.forms.cron}")
    public void execute() {
        if (!isEnable()) return;

        //long startTime = System.currentTimeMillis();

        Integer rs = formsMapper.truncate();
        log.info("remove {} data",rs);

        boolean shouldContinue;
        int pageIndex = 0;
        int pageSize = 1000;
        do {
            shouldContinue = false;

            //Integer maxId = formsMapper.getMaxId();
            //log.info("last max id: {}", maxId);

            //List<FormsDto> records = verintBaseTableDao.getFormsList(maxId);
            List<FormsDto> records = verintBaseTableDao.getFormsListByPage(pageIndex,pageSize);
            log.info("got {} records", records.size());
            if (records.size() == 1000) {
                shouldContinue = true;
            }

            for (FormsDto record : records) {
                try {
                    formsMapper.insert(record);
                } catch (Exception ex) {
                    log.error("Add record to db exception.", ex);
                }
            }

            pageIndex += pageSize;

        }
        while (shouldContinue);
    }
}
